<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生社交媒体与人际关系分析仪表盘</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css?v=3">
    
    <script>
        // 首先定义一个函数，用于加载脚本并返回Promise
        function loadScript(url) {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = url;
                script.onload = () => resolve(script);
                script.onerror = () => reject(new Error(`加载脚本失败: ${url}`));
                document.head.appendChild(script);
            });
        }
        
        // 确保Chart.js只从本地加载，并且实现重试机制
        async function ensureChartLoaded() {
            console.log('开始加载Chart.js');
            let retries = 3;
            let lastError = null;
            
            while (retries > 0) {
                try {
                    // 检查Chart是否已经定义
                    if (typeof Chart !== 'undefined') {
                        console.log('Chart.js已经加载');
                        return true;
                    }
                    
                    // 尝试加载本地版本的Chart.js
                    await loadScript('/static/js/chart.umd.min.js');
                    
                    if (typeof Chart !== 'undefined') {
                        console.log('Chart.js加载成功');
                        return true;
                    }
                } catch (error) {
                    lastError = error;
                    console.error(`Chart.js加载失败，剩余重试次数: ${retries-1}`, error);
                }
                retries--;
                if (retries > 0) {
                    await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒后重试
                }
            }
            
            console.error('Chart.js最终加载失败', lastError);
            return false;
        }
        
        // 在DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', async function() {
            console.log('DOM已加载，开始确保Chart.js可用');
            const chartLoaded = await ensureChartLoaded();
            
            if (chartLoaded) {
                console.log('Chart.js已准备就绪');
                
                // 特征重要性图表
                const featureCtx = document.getElementById('featureChart').getContext('2d');
                // 提供默认的模拟数据，防止模板语法错误
                const features = window.features || [
                  { feature: '平台活跃度', importance: 0.85 },
                  { feature: '内容互动率', importance: 0.72 },
                  { feature: '社交连接数', importance: 0.68 },
                  { feature: '使用时长', importance: 0.63 },
                  { feature: '发帖频率', importance: 0.59 },
                  { feature: '消息回复速度', importance: 0.54 },
                  { feature: '内容多样性', importance: 0.48 },
                  { feature: '社交圈层广度', importance: 0.42 }
                ];
                
                const featureNames = features.slice(0, 8).map(f => f.feature);
                const importances = features.slice(0, 8).map(f => f.importance);
                
                // 直接使用Chart对象创建图表
                new Chart(featureCtx, {
                    type: 'bar',
                    data: {
                        labels: featureNames,
                        datasets: [{
                            label: '重要性系数',
                            data: importances,
                            backgroundColor: 'rgba(54, 162, 235, 0.7)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '重要性系数'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '影响因素'
                                },
                                ticks: {
                                    maxRotation: 45,
                                    minRotation: 45
                                }
                            }
                        },
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return `重要性系数: ${context.parsed.y.toFixed(4)}`;
                                    }
                                }
                            }
                        }
                    }
                });
                
                // 平台用户数量对比图表
                const platformCtx = document.getElementById('platformChart').getContext('2d');
                // 提供默认的模拟数据，防止模板语法错误
                const platformData = window.platformData || {
                  '微信': { user_count: 1200000000 },
                  'QQ': { user_count: 800000000 },
                  '微博': { user_count: 530000000 },
                  '抖音': { user_count: 600000000 },
                  '知乎': { user_count: 250000000 }
                };
                
                const platforms = Object.keys(platformData);
                const userCounts = platforms.map(p => platformData[p].user_count);
                
                // 直接使用Chart对象创建图表
                new Chart(platformCtx, {
                    type: 'bar',
                    data: {
                        labels: platforms,
                        datasets: [{
                            label: '用户数量',
                            data: userCounts,
                            backgroundColor: 'rgba(75, 192, 192, 0.7)',
                            borderColor: 'rgba(75, 192, 192, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '用户数量'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '平台'
                                }
                            }
                        }
                    }
                });
                
                // 平台心理健康评分图表
                const mentalHealthCtx = document.getElementById('mentalHealthChart').getContext('2d');
                const mentalHealthScores = platforms.map(p => platformData[p].avg_mental_health || 0);
                
                new Chart(mentalHealthCtx, {
                    type: 'radar',
                    data: {
                        labels: platforms,
                        datasets: [{
                            label: '心理健康评分',
                            data: mentalHealthScores,
                            backgroundColor: 'rgba(153, 102, 255, 0.2)',
                            borderColor: 'rgba(153, 102, 255, 1)',
                            pointBackgroundColor: 'rgba(153, 102, 255, 1)',
                            pointBorderColor: '#fff',
                            pointHoverBackgroundColor: '#fff',
                            pointHoverBorderColor: 'rgba(153, 102, 255, 1)'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            r: {
                                min: 0,
                                max: 10,
                                ticks: {
                                    stepSize: 2
                                }
                            }
                        }
                    }
                });
                
                // 平台成瘾性评分图表
                const addictionCtx = document.getElementById('addictionChart').getContext('2d');
                const addictionScores = platforms.map(p => platformData[p].avg_addiction_score || 0);
                
                new Chart(addictionCtx, {
                    type: 'line',
                    data: {
                        labels: platforms,
                        datasets: [{
                            label: '成瘾性评分',
                            data: addictionScores,
                            fill: false,
                            backgroundColor: 'rgba(255, 99, 132, 0.8)',
                            borderColor: 'rgba(255, 99, 132, 1)',
                            tension: 0.3,
                            pointBackgroundColor: 'rgba(255, 99, 132, 1)'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 10,
                                title: {
                                    display: true,
                                    text: '成瘾性评分'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '平台'
                                }
                            }
                        }
                    }
                });
                
                // 国家使用时长图表
                const countryUsageCtx = document.getElementById('countryUsageChart').getContext('2d');
                // 提供默认的模拟数据，防止模板语法错误
                const countryData = window.countryData || {
                  '中国': { avg_daily_usage: 3.5 },
                  '美国': { avg_daily_usage: 2.8 },
                  '日本': { avg_daily_usage: 2.3 },
                  '韩国': { avg_daily_usage: 3.1 },
                  '英国': { avg_daily_usage: 2.5 }
                };
                const countries = Object.keys(countryData);
                const avgUsages = countries.map(c => countryData[c].avg_daily_usage || 0);
                
                // 直接使用Chart对象创建图表
                new Chart(countryUsageCtx, {
                    type: 'bar',
                    data: {
                        labels: countries,
                        datasets: [{
                            label: '平均每日使用时长(小时)',
                            data: avgUsages,
                            backgroundColor: 'rgba(54, 162, 235, 0.7)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '使用时长(小时)'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '国家'
                                }
                            }
                        }
                    }
                });
                
                // 国家学习影响图表
                const countryImpactCtx = document.getElementById('countryImpactChart').getContext('2d');
                const impactRates = countries.map(c => countryData[c].academic_impact_rate || 0);
                
                new Chart(countryImpactCtx, {
                    type: 'bar',
                    data: {
                        labels: countries,
                        datasets: [{
                            label: '学习成绩受影响比例(%)',
                            data: impactRates,
                            backgroundColor: 'rgba(255, 99, 132, 0.7)',
                            borderColor: 'rgba(255, 99, 132, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 100,
                                title: {
                                    display: true,
                                    text: '受影响比例(%)'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '国家'
                                }
                            }
                        }
                    }
                });
                
                // 平台学习影响图表
                const platformAcademicImpactCtx = document.getElementById('platformAcademicImpactChart').getContext('2d');
                const academicImpactRates = platforms.map(p => platformData[p].academic_impact_rate || 0);
                
                // 直接使用Chart对象创建图表
                new Chart(platformAcademicImpactCtx, {
                    type: 'bar',
                    data: {
                        labels: platforms,
                        datasets: [{
                            label: '学习成绩受影响比例(%)',
                            data: academicImpactRates,
                            backgroundColor: 'rgba(255, 159, 64, 0.7)',
                            borderColor: 'rgba(255, 159, 64, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                max: 100,
                                title: {
                                    display: true,
                                    text: '受影响比例(%)'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '平台'
                                }
                            }
                        }
                    }
                });
            } else {
                console.error('无法加载Chart.js，图表功能将不可用');
                alert('无法加载Chart.js，图表功能将不可用');
            }
        });
    </script>
    <style>
        body { 
            font-family: 'Microsoft YaHei', sans-serif; 
            background-color: #f8f9fa;
        }
        .metric-card { 
            transition: transform 0.3s, box-shadow 0.3s; 
            height: 100%;
        }
        .metric-card:hover { 
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .chart-container { 
            position: relative; 
            height: 350px;
        }
        .card { 
            margin-bottom: 20px;
            border-radius: 8px;
            overflow: hidden;
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
        .navbar {
            border-radius: 0 0 8px 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .section-title {
            font-weight: 600;
            margin-bottom: 20px;
            color: #333;
        }
        .loading-spinner {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 9999;
        }
    </style>
</head>
<body>
    <!-- 加载指示器 -->
    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    </div>
    
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">学生社交媒体与人际关系分析系统</a>
            <div class="collapse navbar-collapse">
                <div class="navbar-nav">
                    <a class="nav-link active" href="/">仪表盘</a>
                    <a class="nav-link" href="/about">关于</a>
                </div>
                <button id="runAnalysisBtn" class="btn btn-light ms-auto">运行完整分析</button>
            </div>
        </div>
    </nav>
    
    <div class="container mt-5">
        <h1 class="text-center mb-5 section-title">学生社交媒体与人际关系深度分析报告</h1>
        
        <!-- 模型指标卡片 -->
        <div class="row mb-5">
            <div class="col-md-3">
                <div class="card metric-card text-center bg-light">
                    <div class="card-body">
                        <h5 class="card-title text-primary">准确率</h5>
                        <p class="card-text display-4">{{ '%.1f' | format(accuracy * 100) }}%</p>
                        <p class="card-text text-muted">模型预测准确率</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card text-center bg-light">
                    <div class="card-body">
                        <h5 class="card-title text-success">精确率</h5>
                        <p class="card-text display-4">{{ '%.1f' | format(precision * 100) }}%</p>
                        <p class="card-text text-muted">预测正面案例准确率</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card text-center bg-light">
                    <div class="card-body">
                        <h5 class="card-title text-warning">召回率</h5>
                        <p class="card-text display-4">{{ '%.1f' | format(recall * 100) }}%</p>
                        <p class="card-text text-muted">负面影响人群识别率</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card text-center bg-light">
                    <div class="card-body">
                        <h5 class="card-title text-danger">F1分数</h5>
                        <p class="card-text display-4">{{ '%.2f' | format(f1_score) }}</p>
                        <p class="card-text text-muted">综合评价指标</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 主要分析结果区域 -->
        <div class="row">
            <!-- 左侧：特征重要性 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3>关键影响因素分析</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="featureChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：平台对比 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h3>平台使用对比</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="platformChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 第二行图表：心理健康和成瘾性 -->
        <div class="row mt-4">
            <!-- 左侧：平台心理健康 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h3>各平台心理健康评分</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="mentalHealthChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：平台成瘾性 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-warning text-white">
                        <h3>各平台成瘾性评分</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="addictionChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 国家分析图表 -->
        <div class="row mt-4">
            <!-- 左侧：各国使用时长 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3>各国社交媒体使用时长对比</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="countryUsageChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：各国学习影响 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-danger text-white">
                        <h3>各国学习成绩受影响比例</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="countryImpactChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 平台学习影响对比 -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header bg-warning text-white">
                        <h3>各平台学习成绩受影响比例</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="platformAcademicImpactChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 理论框架部分 -->
        <div class="row mt-5">
            <div class="col-md-12">
                <div class="card bg-primary bg-opacity-10">
                    <div class="card-header bg-primary text-white">
                        <h3>系统性理论框架</h3>
                    </div>
                    <div class="card-body">
                        <h4 class="card-title text-primary mb-3">{{ theoretical_framework.name }}</h4>
                        
                        <div class="mb-4">
                            <h5 class="text-info">核心发现</h5>
                            <ul class="list-group">
                                {% for finding in theoretical_framework.core_findings %}
                                <li class="list-group-item">{{ loop.index }}. {{ finding }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                        
                        <div class="mb-4">
                            <h5 class="text-info">理论假设</h5>
                            <ul class="list-group">
                                {% for hypothesis in theoretical_framework.theoretical_hypotheses %}
                                <li class="list-group-item">{{ loop.index }}. {{ hypothesis }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                        
                        <div>
                            <h5 class="text-info">理论贡献</h5>
                            <ul class="list-group">
                                {% for contribution in theoretical_framework.theoretical_contributions %}
                                <li class="list-group-item">{{ loop.index }}. {{ contribution }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 结论总结 -->
        <div class="row mt-5">
            <div class="col-md-12">
                <div class="card bg-info bg-opacity-10">
                    <div class="card-body">
                        <h4 class="card-title text-info">核心发现</h4>
                        <p class="card-text">1. 使用时长是影响学生心理健康和学习成绩的最重要因素</p>
                        <p class="card-text">2. 成瘾倾向是社交媒体负面影响的关键中介变量</p>
                        <p class="card-text">3. 不同平台对学生的影响存在显著差异，TikTok用户学习成绩受影响比例最高</p>
                        <p class="card-text">4. 睡眠质量与社交媒体使用密切相关，建议保持充足睡眠</p>
                        <p class="card-text">5. 深度学习模型能够有效预测学习成绩受影响情况，AUC分数达0.8972</p>
                        <p class="card-text">6. 国家文化背景对社交媒体使用模式和影响有显著调节作用</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        
        // 运行分析按钮事件
        document.getElementById('runAnalysisBtn').addEventListener('click', function() {
            // 显示加载指示器
            document.getElementById('loadingSpinner').style.display = 'block';
            
            // 发送请求运行分析
            fetch('/run_analysis', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载指示器
                document.getElementById('loadingSpinner').style.display = 'none';
                
                // 显示结果消息
                if (data.status === 'success') {
                    alert('分析已成功完成！页面将刷新以显示最新结果。');
                    location.reload();
                } else {
                    alert('分析失败: ' + data.message);
                }
            })
            .catch(error => {
                // 隐藏加载指示器
                document.getElementById('loadingSpinner').style.display = 'none';
                alert('分析请求失败: ' + error);
            });
        });
    </script>
</body>
</html>